//-----处理业务逻辑-----//
const db = require('./db.js')
//svgCaptcha
const svgCaptcha = require('svg-captcha')
var captchaCode = ""  //定义变量
exports.start = (req, res) => {
}

// 登录注册处理
exports.login = (req, res) => {
    let username = req.body.username
    let pwd = req.body.password
    let code = req.body.code.toLowerCase()  //验证码，转小写
    console.log("登录输出:" + username, pwd, code, captchaCode)
    // 查询语句
    if (code == captchaCode) {
        let sql = 'select * from login where username = ?'
        db.base(sql, username, (result) => {
            if (!result.length) {
                return res.json({ status: 0, msg: '登录失败' })
            } else {
                // [ RowDataPacket { password: '123', username: 'admin', id: 1 } ]
                if (result[0].password == pwd) {
                    return res.json({ status: 1, msg: '登录成功' })
                }
                return res.json({ status: 2, msg: '密码错误' })
            }
        })
    }else{
        return res.json({ status: 4, msg: '验证码错误' })
    }
}
exports.register = (req, res) => {
    console.log(req.body)
    res.send('测试')
}
//生成验证码
exports.captcha = (req, res) => {
    const cap = svgCaptcha.create({
        // 翻转颜色
        inverse: false,
        // 验证码字符中排除 0o1i
        ignoreChars: '0o1i',
        // 字体大小
        fontSize: 36,
        // 噪声线条数
        noise: 3,
        // 宽度
        width: 80,
        // 高度
        height: 30,
    });
    req.session.captcha = cap.text; // session 存储验证码数值
    // res.cookie('captcha', req.session.captcha); 
    console.log(Date.now())
    console.log("后台生成的session.captcha:" + req.session.captcha)
    captchaCode = req.session.captcha.toLowerCase();  //赋值，登录验证使用
    res.type('svg');    //响应的类型
    res.send(cap.data)  //发送数据
}



